if (!floaty.checkPermission()) {
    // 没有悬浮窗权限，提示用户并跳转请求
    toast(
        '本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。'
    );
    floaty.requestPermission();
    exit();
} else {
    toastLog('已有悬浮窗权限');
}

// 标记浮动窗口
var markFloat = (text, position) => {
    var w = floaty.window(
        <frame gravity="center">
            {/* <text id="text">⭕️</text> */}
            <text id="text">text</text>
        </frame>
    );
    w.text.setText(text + '');
    w.setPosition(position[0], position[1]);
    return w;
};

var w21, w22, w31, w32;
var step2Clear = () => {
    if (!w21) return;
    w21.close();
    w22.close();
    w31.close();
    w32.close();
};
var step2Resolve = () => {
    if (id('com.wm.dmall:id/content').findOne().children().size() === 4) {
        console.log('children 4');
        step2Clear();
        return;
    }
    if (!w21) {
        var yyXY1 = [width * 0.5, height * 0.84];
        var yyXY2 = [width * 0.75, height - 350];
        w21 = markFloat('2.1', yyXY1);
        w22 = markFloat('2.2', yyXY2);
        var cfXY1 = [width * 0.5, height * 0.65];
        var cfXY2 = [width * 0.75, height * 0.5 + 324];
        w31 = markFloat('3.1', cfXY1);
        w32 = markFloat('3.2', cfXY2);
    }

    setTimeout(() => {
        step2Resolve();
    }, 5);
};

var w41, w41, w51, w52;
var step3Clear = () => {
    if (!w41) return;
    w41.close();
    w42.close();
    w51.close();
    w52.close();
};
var step3Resolve = () => {
    if (id('com.wm.dmall:id/content').findOne().children().size() === 4) {
        if (!w41) {
            var yyXY1 = [width * 0.5, height * 0.7];
            var yyXY2 = [width * 0.75, 1512];
            w41 = markFloat('4.1', yyXY1);
            w42 = markFloat('4.2', yyXY2);
            var cfXY1 = [width * 0.5, height * 0.54];
            var cfXY2 = [width * 0.75, height * 0.5 + 100];
            w51 = markFloat('5.1', cfXY1);
            w52 = markFloat('5.1', cfXY2);
        }
    }
    setTimeout(() => {
        step3Resolve();
    }, 5);
};

try {
    var step = 1;
    console.log(device.width, device.height, device.getVirtualBarHeigh());
    var width = device.width;
    var height = device.height;
    // click(900, 850);
    // click(1000, 900);
    var qgXY = [0.83 * width, 0.39 * height];

    var w1 = markFloat(1, qgXY);
    console.log('step', step++);

    if (text('茅台预约抢购').findOne()) {
        console.log('step', step++);
        w1.close();
        step2Resolve();
    }
    step3Resolve();

    setInterval(() => {}, 2000);
} catch (error) {
    console.log('error', error);
}
